import React, {useRef, useState} from "react";
import {ActionType, PageContainer, ProColumns, ProTable} from "@ant-design/pro-components";
import {Button, Divider, message, Popconfirm, Space, Typography} from "antd";
import {deleteLog, logQueryList} from "@/services/logService";
import CreateModal from "./components/CreateModal";
import UpdateModal from "./components/UpdateModal";

const AdminLogPage: React.FC<unknown> = () =>{
    const actionRef = useRef<ActionType>();
    const [createModalVisible, setCreateModalVisible] = useState<boolean>(false);
    const [updateModalVisible, setUpdateModalVisible] = useState<boolean>(false);
    const [updateData, setUpdateData] = useState<LogType.Log>(
        {} as LogType.Log,
    );

    const doDelete = async (log:LogType.Log)=>{
        const hide = message.loading('正在删除');
        if(!log?.id){return;}

        await deleteLog(log.id).then(res=>{
            message.success("删除成功")
        }).catch(e=>{
            message.error(e.message)
        }).finally(()=>{
            hide();
        })
    }

    /**
     * 表格列表
     */
    const columns: ProColumns<LogType.Log>[] = [
        {
            title: 'id',
            dataIndex: 'id',
            valueType: 'index',
        },
        {
            title: '请求IP',
            dataIndex: 'requestIp',
            valueType: 'text',
            formItemProps: {
                rules: [
                    {
                        required: true,
                        message: '必须填写IP地址'
                    }
                ]
            },
            fieldProps: {
                allowClear: false
            }
        },
        {
            title: '请求参数',
            hideInSearch:true,
            dataIndex: 'requestParam',
            valueType: 'text',
        },
        {
            title: '请求路径',
            dataIndex: 'requestUrl',
            valueType: 'text',
            width:130
        },
        {
            title: '耗时(ms)',
            dataIndex: 'cost',
            valueType: 'digit',
        },
        {
            title: '请求时间',
            dataIndex: 'createTime',
            hideInSearch:true,
            hideInForm:true,
            width:180,
            valueType: 'dateTime',
        },
        {
            title: '操作',
            dataIndex: 'option',
            valueType: 'option',
            width:120,
            render: (_, record) => (
                <Space split={<Divider type="vertical"/>}>
                    <Typography.Link
                        onClick={() => {
                            setUpdateData(record);
                            setUpdateModalVisible(true);
                        }}
                    >
                        修改
                    </Typography.Link>

                    <Popconfirm
                        title="您确定要删除么？"
                        onConfirm={() => doDelete(record)}
                        okText="确认"
                        cancelText="取消"
                    >
                        <Typography.Link type="danger">删除</Typography.Link>
                    </Popconfirm>
                </Space>
            ),
        },
    ]

    return(
        <PageContainer>
            <ProTable<LogType.Log>
                headerTitle="日志管理"
                actionRef={actionRef}
                rowKey="id"
                search={{
                    labelWidth: 'auto',
                    defaultCollapsed: false,
                }}
                pagination={{
                    showSizeChanger: true,
                    pageSize:10
                }}
                toolBarRender={() => [
                    <Button
                        key="1"
                        type="primary"
                        onClick={() => setCreateModalVisible(true)}
                    >
                        新建
                    </Button>,
                ]}
                request={async (params, sorter) => {
                    const searchParams:LogType.LogQueryRequest = {
                        ...params,
                    };
                    // eslint-disable-next-line guard-for-in
                    for (const key in sorter) {
                        searchParams.sortField = key;
                        searchParams.sortOrder = sorter[key] as any;
                    }
                    const {data, code} = await logQueryList(searchParams);
                    return {
                        data: data?.records || [],
                        success: code === 0,
                        total: data.total,
                    } as any;
                }}
                columns={columns}
            />
            <CreateModal
                modalVisible={createModalVisible}
                columns={columns}
                onSubmit={() => {}}
                onCancel={() => setCreateModalVisible(false)}
            />
            <UpdateModal
                modalVisible={updateModalVisible}
                oldData={updateData}
                columns={columns}
                onSubmit={() => {}}
                onCancel={() => setUpdateModalVisible(false)}
            />
        </PageContainer>
    )

}


export default AdminLogPage;